/**
 * @name: TheUpload
 * @description: 上传组件封装
 * @upTime: 2023--11--21
 * @props { disabled }  Boolean     是否禁用上传控件
 * @props { len }       Number      上传数量
 * @props { maxSize }   Number      上传的文件大小     - 单位M
 * @props { accept }    Array       控制上传的文件类型
 * @props { fileList }  Array       数据集合
 * @props { extra }     String      额外的提示信息
 * @props { accept }    Array       限制上传的文件类型
 * @props { label }     String      Form.Item 标签的文本
 * @props { name }      String      Form.Item 字段名
 *
 **/
import {
    ProForm,
    ProFormUploadButton,
    ProFormUploadDragger,
} from '@ant-design/pro-components';

import React, {useState, useEffect} from 'react';
import {Form, Upload, message, Modal} from 'antd';
import {PlusOutlined} from '@ant-design/icons';

const BASE_URL = import.meta.env.VITE_APP_BASE_API
const RSnetToken = sessionStorage.getItem('RSnetToken')
const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
const Index = (props) => {
    const [fileList, setFileList] = useState([]);
    const [len, setLen] = useState(5);
    const [disabled, setDisabled] = useState(false);
    const [maxSize, setMaxSize] = useState(5);
    const [extra, setExtra] = useState();
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const [imageExtensions, setImageExtensions] = useState([
        'image/jpeg', 'image/png', 'image/webp', 'image/svg+xml'
    ]);

    useEffect(() => {
        props.len && setLen(props.len);
        props.disabled && setDisabled(props.disabled);
        props.maxSize && setMaxSize(props.maxSize);
        props.accept && setImageExtensions(props.accept);
        if (props.extra) {
            setExtra(props.extra)
        } else if (props.extra === null) {
            setExtra('')
        } else {
            setExtra(`上传文件大小限制${maxSize}MB,文件格式限制 ${imageExtensions.map(item => item.split('/')[1])}`)
        }
    }, [])
    const normFile = (e) => {
        // console.log(e)
        if (Array.isArray(e)) {
            return e;
        }
        setFileList(e?.fileList)
        if (e?.fileList.length) {
            return e?.fileList.map(item => {
                if (item.status === "done" && item.response) {
                    return item.response.data
                } else {
                    return item.url
                }
            }).toString();
        } else {
            return undefined
        }
    };

    const valueFile = (e) => {
        // console.log(e)
        if (e) {
            let a = e?.split(',').map((item, index) => {
                return {
                    uid: `-${index + 1}`,
                    name: item.substring(item.lastIndexOf('/') + 1),
                    status: 'done',
                    url: item,
                }
            })
            if (fileList.length !== a.length) {
                setFileList(a)
            }
            return a
        } else {
            return []
        }
    }
    const checkFileSize = (file, fileList) => {
        if (!imageExtensions.includes(file.type)) {
            message.info(`上传文件格式不正确`)
            return Upload.LIST_IGNORE
        }
        if (file.size / 1024 / 1024 >= (maxSize || 5)) {
            message.info(`上传文件大小最大为${maxSize}MB`)
            return Upload.LIST_IGNORE
        }
    }
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    }
    return (
        <>
            <ProFormUploadButton
                // name={["images"]}
                // label={props.label ? (props.label || "Upload") : null}
                max={len}
                noStyle
                fieldProps={{
                    name: 'file',
                    listType: 'picture-card',
                    headers: {RSnetToken}
                }}
                // formItemProps={{
                //     // valuePropName: "fileList",
                //     // rules: props.rules ? props.rules : []
                // }}
                // convertValue={(e,namePath)=>{
                //     // value.split(",")
                //     console.log(e,namePath)
                //     if (Array.isArray(e)) {
                //         return e;
                //     }
                //     if (e) {
                //         return e.map(item => {
                //             if (item.status === "done" && item.response) {
                //                 return item.response.data
                //             } else {
                //                 return item.url
                //             }
                //         }).toString();
                //     } else {
                //         return undefined
                //     }
                // }}
                // transform={(value) => {
                //     console.log(value)
                //     // return {
                //     //     date: moment(value).unix(),
                //     // };
                // }}
                action={BASE_URL + "management/oss/image/upload"}
                extra={extra}
            />
            {/*<Form.Item*/}
            {/*    label={props.label ? (props.label || "Upload") : null}*/}
            {/*    name={props.name || "Upload"}*/}
            {/*    valuePropName="fileList"*/}
            {/*    getValueFromEvent={normFile}*/}
            {/*    getValueProps={valueFile}*/}
            {/*    rules={props.rules ? props.rules : []}*/}
            {/*    extra={extra}*/}
            {/*>*/}
            {/*    <Upload*/}
            {/*        action={BASE_URL + "management/oss/image/upload"}*/}
            {/*        listType="picture-card"*/}
            {/*        headers={{RSnetToken}}*/}
            {/*        fileList={fileList}*/}
            {/*        disabled={disabled}*/}
            {/*        beforeUpload={checkFileSize}*/}
            {/*        onPreview={handlePreview}*/}
            {/*    >*/}
            {/*        {*/}
            {/*            (fileList.length >= len || disabled) ? null : <div>*/}
            {/*                <PlusOutlined/>*/}
            {/*                <div style={{marginTop: 8}}>Upload</div>*/}
            {/*            </div>*/}
            {/*        }*/}
            {/*    </Upload>*/}
            {/*</Form.Item>*/}
            <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={() => setPreviewOpen(false)}>
                <img
                    alt="preview"
                    style={{
                        width: '100%',
                    }}
                    src={previewImage}
                />
            </Modal>
        </>
    )
};

export default Index;
